#!/usr/bin/perl
#
# Write the per-country lists of Linux users
# Depends on a pre-sorted file holding all the persons that should
# go into the list.
#
# NEW FEATURE: generate a GIF image on development of that country
#
use POSIX;
use Reportsub;

$allentries = 9999999; # 9 million
$maxcount = $allentries;

while ($ARGV[0] =~ /^-/) {
    $opt = shift;
    if ($opt eq "-max") {
	$maxcount = shift;
    }
}
$date = `date`;
chop $date;

if ($maxcount < $allentries) {
    print STDERR "Using test Web\n";
    $targetdir = "test-www";
} else {
    print STDERR "Updating real Web\n";
    $targetdir = "www/bycountry/";
}
$sortitlast = "zzzz";

print STDERR "Loading country info\n";
getcountryinfo();
loadstates();

print STDERR "Reading records\n";
while (<>) {
    last if ($skip + $count > $maxcount);
    chop;
    ($key, $country, $state, $city, $name, $email, $maypublish) = split("\t");
    if ($maypublish ne "YES") {
	#print STDERR "Skip - $maypublish\n";
	++ $skip;
	++ $countrytable{$country}{skip};
	next;
    }
    # Some other reasons to skip records
    if (!$name) {
	#print STDERR "$key: No name\n";
	++ $skip;
        ++ $nonameskip;
	next;
    }
    if (!$longname{$country}) {
	print STDERR "$key: No country name for country ",
	$country, ", skip\n";
	++ $skip;
	next;
    }
    ++ $count;
    print STDERR "$count/$skip\r" if ($count + $skip) % 100 == 0;
    # ------------- Write the result ----------

    if ($country ne $prevcountry) {
	if ($prevcountry) {
	    &closefile;
	}
	# Do NOT create file for country names we don't know about.
	if (!$longname{$country}) {
	    print STDERR
		"*E* No country name for country code $country, skip\n";
	    $prevcountry = "";
	    next;
	}
	openfile("$targetdir/$country.php");

	print OUT "<html><head>\n";
	print OUT "<title>Linux users in $country</title>\n";
	print OUT "<body bgcolor=white>\n";
	print OUT "<h1><img src=\"/gifs/Logo-small.png\" alt=\"Linux Counter Logo\">\n";
	print OUT "Linux users in $longname{$country} ($country)</h1>\n";
	print OUT "This file generated: $date<p>\n";
	# Print some country info
	# Plot of registrations - generated via "system" call (nekulturny!)
        print OUT "<img src=\"$country.gif\"><p>\n";
	system("tools/plothistory $country < temp/country.story | gnuplot > $targetdir/$country.gif"); 
print OUT <<EoF;
<table border=0 width="80%">
<tr><td>
EoF
	print OUT "Population: $population{$country} million<br>\n";
        print OUT "Hostcount: $hostcount{$country}<br>\n";
	print OUT "Linux users: $usercount{$country}<br>\n";
	if ($population{$country} > 0) {
	    $density = $usercount{$country} / $population{$country};
	    printf OUT "Linux density: %5.2f users/million<br>\n", $density;
	} else {
	    printf OUT "Linux density not avaliable\n";
	}
        if ($hostcount{$country} > 0) {
	    printf OUT "Linux users per 1000 IP hosts: %5.2f<br>\n",
	       $usercount{$country} * 1000 / $hostcount{$country};
	}
	print OUT <<EoF;
<td align=right>
<table border>
<tr><td><a href="/enter-person.php"><strong><font size=5>
Count me too!</font></strong></a>
</table>
</table>
EoF
	print OUT "<p>\n";
	if ($hasstates{$country}) {
	    print OUT "<ul>\n";
	    for $state (split(":", $statelist{$country})) {
		($upstate = $state) =~ tr/a-z/A-Z/;
		if ($statename{$country, $upstate}) {
		    print OUT	
		    "<li><a href=#$state>$statename{$country, $upstate}</a>\n";
		}
	    }
	    print OUT "</ul>\n";
	}
	$prevcity = "---"; $prevstate = "---"; # magic tokens
	$prevcountry = $country;
    }
    if ($hasstates{$country} && $state ne $prevstate) {	
	&closelist;
	print STDERR "Printing for $country $state\n";
	if ($state ne $sortitlast) {
	    ($upstate = $state) =~ tr/a-z/A-Z/;
	    if (!$statename{$country, $state}) {
		print STDERR "No statename for $country $state\n";
	    }
	    print OUT
		"<h2><a name=$state>$statename{$country, $state} ($upstate)</a></h2>\n";
	} else {
	    print OUT "<h2>No state/province given</h2>\n";
	}
	$prevcity = "---";
	$prevstate = $state;
    }
    if ("\L$city" ne "\L$prevcity") {
	&closelist;
	if ($city ne $sortitlast) {
	    print OUT "<h3>$city</h3>\n";
	} else {
	    print OUT "<h3>No city given</h3>\n";
	}
	if ($usetable) {
	    print OUT "<table>\n";
	} else {
	    print OUT "<ul>\n";
	}
	$prevcity = $city;
    }
    $name =~ s/</&lt;/;
    $name =~ s/>/&gt;/;
    if ($usetable) {
	print OUT "<tr><th align=left>$name<td align=left>$email\n";
    } else {
	print OUT "<li><strong>$name</strong> $email <!-- $key -->\n";
    }
    ++ $personcount{$country};
    if ($personcount{$country} == 100) {
	if ($usetable) {
	    print OUT "<tr><th align=left>Spam Trap<td align=left>spamtrap&#x40;counter.li.org\n";
	} else {
	    print OUT "<li><strong>Spam Trap</strong> spamtrap&#x40;counter.li.org\n";
	    print OUT "<li><strong>Ad Recipient</strong> reklame&#x40;counter.li.org\n";
	}
    }
    $listopen = 1;
}
&closefile;

# note that this op does NOT go via a tempfile...
open(OUT, ">$targetdir/index.php");
print OUT <<EoF;
<html><head>
<title>Linux users by country</title>
</head><body bgcolor=white>
<h1>Countries with Linux users in them</h1>
This file generated: $date
<p>
<a href=legal.php>Copyright &copy; Harald T. Alvestrand, Linux Counter</a>
To be used for personal contact information only!
<ul>
EoF

for $country (sort(keys(%personcount))) {
    next if $personcount{$country} == 0;
    print OUT "<li> <a href=$country.php>$country $longname{$country}</a>\n";
    print OUT "($personcount{$country} people listed)\n";
}
print OUT "</body></html>\n";
close OUT;

print STDERR "$count records counted, $skip records skipped\n";
print STDERR "$nonameskip records without a name\n";


sub closelist {
    if ($listopen) {
	if ($usetable) {
	    print OUT "</table>\n";
	} else {
	    print OUT "</ul>\n";
	}
    }
    $listopen = 0;
}


# ----- Open/close files.
# NOTE: The filehandle OUT and the variable $realfilename are globals
# ------------------
sub openfile {
    $realfilename = shift;

    if (!$realfilename) {
	open(OUT, ">/dev/null");
    } else {
	open(OUT, ">$realfilename.temp")
	    || die "Unable to open $realfilename.temp\n";
    }
}

sub closefile {
    local($realfile);

    return if (!$realfilename);
    &closelist;
    print OUT <<EoF;
<hr>
<a href="/index.php">
<img src="/gifs/leftsign.gif">Back to counter
main page</a>
<hr>
<a href="legal.php">Copyright &copy; Harald T. Alvestrand, Linux Counter</a>
</body></html>
EoF
    close(OUT);
    unlink($realfilename);
    rename("$realfilename.temp", $realfilename)
            || die "Rename $realfilename failed\n";
}


